#include "../ui.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <stdbool.h>

static bool btn_pressed = false; // 用于跟踪按钮状态

// 定时器回调函数，用于重置按钮状态
static void reset_btn_pressed(lv_timer_t *timer)
{
  btn_pressed = false; // 重置按钮状态
  lv_timer_del(timer); // 删除定时器
}



static void btn_event_cb(lv_event_t *e)
{
  lv_event_code_t code = lv_event_get_code(e);
  lv_obj_t *btn = lv_event_get_target(e);
  uint32_t id = lv_btnmatrix_get_selected_btn(btn);
  if (code == LV_EVENT_VALUE_CHANGED)
  {
    if (!btn_pressed) // 检查按钮是否已经被按下
    {
      btn_pressed = true; // 标记按钮已被按下
      const char *btn_text = lv_btnmatrix_get_btn_text(btn, lv_btnmatrix_get_selected_btn(btn));

      if (strcmp(btn_text, "返回") == 0) /* 切换到功能1界面 */
      {
        LED_write("gpio4/value", "0");
        ui_Home_screen_init();
        lv_scr_load_anim(ui_Home, LV_SCR_LOAD_ANIM_FADE_ON, 200, 0, true);
      }
      lv_timer_create(reset_btn_pressed, 100, NULL);
    }
  }
}

static void anim_y_cb(void * var, int32_t v)
{
    lv_obj_set_y(var, v);
}

static char ketboard_anim=0;

static void ta_event_cb(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *ta = lv_event_get_target(e);
    lv_obj_t *kb = lv_event_get_user_data(e);

    if (code == LV_EVENT_FOCUSED)
    {
        lv_keyboard_set_textarea(kb, ta);
        // lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);

        if(!ketboard_anim)
        {
           // 上滑动画显示键盘
          lv_anim_t a;
          lv_anim_init(&a); //初始化
          lv_anim_set_var(&a, kb);  //设定容器
          lv_anim_set_time(&a, 1000);  // 动画持续时间为300毫秒
          lv_anim_set_values(&a, 100, -32);
          lv_anim_set_exec_cb(&a, anim_y_cb);
          lv_anim_set_path_cb(&a, lv_anim_path_ease_in_out );
          lv_anim_start(&a);
          ketboard_anim=1;
        }
       

        
    }

    if (code == LV_EVENT_DEFOCUSED)
    {
        lv_keyboard_set_textarea(kb, NULL);

        // 下滑动画隐藏键盘
        lv_anim_t a;
        lv_anim_init(&a); //初始化
        lv_anim_set_var(&a, kb);  //设定容器
        lv_anim_set_time(&a, 1500);  // 动画持续时间为300毫秒
        lv_anim_set_values(&a, -32, 100);
        lv_anim_set_exec_cb(&a, anim_y_cb);
        lv_anim_set_path_cb(&a, lv_anim_path_ease_in_out );
        lv_anim_start(&a);
        ketboard_anim=0;
        // lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
    }
}

static void input_keyboard_wifi(lv_obj_t *parent)
{
  /*Create a keyboard to use it with an of the text areas*/
  lv_obj_t *kb = lv_keyboard_create(parent);
  // lv_obj_align(kb, LV_ALIGN_BOTTOM_MID, 0, -32);
  lv_keyboard_set_mode(kb, LV_KEYBOARD_MODE_NUMBER );
  lv_obj_set_pos(kb, 0, 100);
  // lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);

  /*Create a text area. The keyboard will write here*/
  lv_obj_t *ta;
  ta = lv_textarea_create(parent);
  lv_obj_align(ta, LV_ALIGN_TOP_MID, -50, 50);
  lv_obj_add_event_cb(ta, ta_event_cb, LV_EVENT_ALL, kb);
  lv_textarea_set_placeholder_text(ta, "Password");
  lv_obj_set_size(ta, lv_pct(40), lv_pct(14));

  // ta = lv_textarea_create(parent);
  // lv_obj_align(ta, LV_ALIGN_TOP_RIGHT, -10, 10);
  // lv_obj_add_event_cb(ta, ta_event_cb, LV_EVENT_ALL, kb);
  // lv_obj_set_size(ta, lv_pct(40), lv_pct(30));

  lv_keyboard_set_textarea(kb, ta);
}

static void LED_event_handler(lv_event_t *e)
{
  lv_event_code_t code = lv_event_get_code(e);
  lv_obj_t *obj = lv_event_get_target(e);
  // uint32_t *user_data = e->user_data;
  if (code == LV_EVENT_VALUE_CHANGED)
  {
    if (lv_obj_has_state(obj, LV_STATE_CHECKED) == 1)
    {
      LED_write("gpio4/value", "1");
      // lv_led_on(user_data);
    }
    else
    {
      LED_write("gpio4/value", "0");
      // lv_led_off(user_data);
    }
  }
}

/////////////////
static lv_obj_t *dropdown;

static void wifi_select_event_handler(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t * obj = lv_event_get_target(e);
    if(code == LV_EVENT_VALUE_CHANGED) {
        char buf[32];
        lv_dropdown_get_selected_str(obj, buf, sizeof(buf));
        printf("Option: %s", buf);
        // lv_dropdown_set_text(dropdown, buf);
    }
}

static int is_valid_ssid(const char *ssid)
{
    // 检查SSID中是否包含非打印字符
    // while (*ssid != '\0') 
    // {
        // if (!isprint((unsigned char)*ssid)) 
        if(*ssid != '\\' && *ssid != ' ')
        {
          // printf("%c",*ssid);
            return 1;
        }
        // ssid++;
    // }
  
    return 0;
}

void wifi_scan()
{
    system("wpa_cli scan");
}

void wifi_scan_results()
{
    FILE *fp;
    char path[1035];
    char ssid_list[1024] = "";

    /* 执行命令并打开读取管道 */
    fp = popen("wpa_cli scan_results", "r");
    if (fp == NULL) {
        printf("Failed to run command\n" );
        exit(1);
    }

    /* 读取扫描结果的输出 */
    int line_count = 0;
    while (fgets(path, sizeof(path), fp) != NULL) 
    {
        // 跳过第一行标题
        if (line_count > 0) 
        {
            // 解析每行的SSID
            char *token = strtok(path, "\t");
            int token_count = 0;
            while (token != NULL)  
            {
                if (token_count == 4 && is_valid_ssid(token)) 
                {  // 第五个字段是SSID
                    strcat(ssid_list, token);
                    // strcat(ssid_list, "\n");
                    // printf("%s",token);
                }
                token = strtok(NULL, "\t");
                token_count++;
            }
        }
        line_count++;
    }

    /* 关闭管道 */
    pclose(fp);

    /* 将解析的SSID列表设置到下拉框中 */
    lv_dropdown_set_options(dropdown, ssid_list);
}

extern lv_indev_t *encoder_indev;
void create_dropdown(lv_obj_t *parent)
{
    dropdown = lv_dropdown_create(parent);
    lv_obj_align(dropdown, LV_ALIGN_TOP_MID, -50, 10);
    // lv_dropdown_set_text(dropdown, "Select WiFi");
    lv_obj_add_event_cb(dropdown, wifi_select_event_handler, LV_EVENT_ALL, NULL);

    lv_group_t * g = lv_group_create();
    lv_indev_set_group(encoder_indev, g);
    lv_group_add_obj(g, dropdown);
    lv_group_focus_obj(dropdown);
}
/////////////////

extern unsigned int back_ground_value;

static void create_function_widgets(lv_obj_t *parent)
{
  // 设置背景颜色
  lv_obj_set_style_bg_color(parent, lv_color_hex(back_ground_value), 0);

  // 创建底部按钮
  static const char *btn_map[] = {"返回", ""};
  lv_obj_t *btnm = lv_btnmatrix_create(parent);
  lv_btnmatrix_set_map(btnm, btn_map);
  lv_obj_set_size(btnm, lv_pct(90), lv_pct(25));
  lv_obj_align(btnm, LV_ALIGN_BOTTOM_MID, 0, -40);
  lv_obj_add_event_cb(btnm, btn_event_cb, LV_EVENT_ALL, NULL);

  // 设置按钮样式
  lv_obj_set_style_text_font(btnm, &lv_font_simsun_16_cjk, 0);
  // lv_obj_set_style_bg_color(btnm, lv_color_hex(0x34495e), LV_PART_MAIN);
  lv_obj_set_style_bg_color(btnm, lv_color_hex(0xDBDBDB), LV_PART_MAIN);
  lv_obj_set_style_border_width(btnm, 0, LV_PART_MAIN);
  lv_obj_set_style_radius(btnm, 10, LV_PART_MAIN);
  lv_obj_set_style_text_color(btnm, lv_color_hex(0xecf0f1), LV_PART_ITEMS);
  lv_obj_set_style_bg_color(btnm, lv_color_hex(0x3498db), LV_PART_ITEMS);
  lv_obj_set_style_radius(btnm, 5, LV_PART_ITEMS);

  lv_btnmatrix_set_btn_ctrl_all(btnm, LV_BTNMATRIX_CTRL_CHECKABLE); // 设置所有按钮为可选中状态
  lv_btnmatrix_set_one_checked(btnm, true);                         // 设置按钮矩阵为一次只允许选中一个按钮
  // lv_btnmatrix_set_btn_ctrl(btnm, 0, LV_BTNMATRIX_CTRL_CHECKED);    // 设置第一个数字按钮（“1”）为默认选中

  // 创建第一个按钮
  lv_obj_t *led_btn;
  lv_obj_t *label;

  led_btn = lv_btn_create(parent); // 先创建按钮
  lv_obj_align(led_btn, LV_ALIGN_CENTER, -60, -5);
  label = lv_label_create(led_btn); // 然后在按钮上创建标签
  lv_label_set_text(label, "LED");
  lv_obj_add_flag(led_btn, LV_OBJ_FLAG_CHECKABLE);
  lv_obj_add_event_cb(led_btn, LED_event_handler, LV_EVENT_ALL, NULL);

  // 创建第二个按钮
  lv_obj_t *btn;

  btn = lv_btn_create(parent); // 先创建按钮
  lv_obj_align(btn, LV_ALIGN_CENTER, 35, -5);
  label = lv_label_create(btn); // 然后在按钮上创建标签
  lv_label_set_text(label, "信息");
  lv_obj_set_size(btn, 110, 31);
  lv_obj_set_style_text_font(label, &lv_font_simsun_16_cjk, 0);
  lv_obj_center(label);

  // printf("%d", lv_obj_get_width(btn));

  input_keyboard_wifi(parent);

  lv_obj_t * label_t = lv_label_create(parent);
  lv_label_set_text(label_t, "Hello animations!");
  // lv_obj_set_pos(label_t, 100, 10);
  lv_obj_set_pos(label_t, 0, 20);

  lv_anim_t a;
  lv_anim_init(&a); //初始化
  lv_anim_set_var(&a, label_t);  //设定容器
  lv_anim_set_time(&a, 3000);  // 动画持续时间为300毫秒
  lv_anim_set_values(&a, lv_obj_get_y(label_t), lv_obj_get_y(label_t)+200);
  lv_anim_set_exec_cb(&a, anim_y_cb);
  lv_anim_set_path_cb(&a, lv_anim_path_overshoot);
  lv_anim_start(&a);

  create_dropdown(parent);
  wifi_scan();
  wifi_scan_results();
}

void ui_Screen3_screen_init(void)
{
  ui_Screen3 = lv_obj_create(NULL);
  lv_obj_clear_flag(ui_Screen3, LV_OBJ_FLAG_SCROLLABLE); /// Flags
  create_function_widgets(ui_Screen3);
}
